package com.shwread.android.qysw.activity.task;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.base.BaseActicity;
import com.ciko.code.utils.NetWorkUtils;
import com.ciko.code.utils.Util;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.bean.que.QuestionnaireInfo;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.dialog.NetworkDialog;
import com.shwread.android.ui.widget.refresh.SuperSwipeRefreshLayout;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;

import static android.media.CamcorderProfile.get;

/**
 * 问卷调查列表页
 */
public class QuestionnaireListActivity extends BaseActicity {

    ArrayList<QuestionnaireInfo> queList = new ArrayList<>();

    /**
     * 没有数据
     */
    private TextView tvNotData;
    /**
     * 问卷列表
     */
    private RecyclerView rlvQuestionnaireList;
    /**
     * 刷新布局
     */
    private SuperSwipeRefreshLayout mRefreshLayout;

    //刷新头
    private ProgressBar progressBar;
    private TextView textView;
    private ImageView imageView;
    //加载尾
    private ProgressBar footerProgressBar;
    private TextView footerTextView;
    private ImageView footerImageView;
    private QuestionAdapter questionAdapter;

    @Override
    protected void initTopBar() {
        setTitle("问卷调查");
        enableNavLeftImg();
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_questionnaire_list);
    }

    @Override
    protected void initView() {
        rlvQuestionnaireList = findViewByID(R.id.rlv_questionnaire_list);
        mRefreshLayout = findViewByID(R.id.layout_swipe_refresh);
        tvNotData = findViewByID(R.id.tv_not_data);

        mRefreshLayout.setHeaderView(createHeaderView());
        mRefreshLayout.setFooterView(createFooterView());
    }

    @Override
    protected void initAdapter() {

    }

    @Override
    protected void initDates() {
        getData(0);
        questionAdapter = new QuestionAdapter();
        rlvQuestionnaireList.setAdapter(questionAdapter);
    }

    /**
     * 加载数据
     *
     * @param status 0-初次加载,1-刷新,2-下拉加载
     */
    private void getData(int status) {
        if (!NetWorkUtils.isConnected(this)) {
            if (status == 0) {
                new NetworkDialog(this).show();
            } else {
                Util.showToast(this, "网络错误，请检查网络");
            }
            return;
        }
        switch (status) {
            case 0:
                //进度条
                queList.clear();
                break;
            case 1:
                queList.clear();
                break;
            case 2:
                break;
        }
        NewActionHelp.qryQuestionnaireList(this, new ObjectHttpResponseHandler<ArrayList<QuestionnaireInfo>>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("sss", "失败--" + s);
                refurbish();
            }

            @Override
            public void onSuccess(int i, Header[] headers, ArrayList<QuestionnaireInfo> questionnaireInfoList, String s) {
                Log.e("sss", "成功--" + s);
                if (questionnaireInfoList != null && questionnaireInfoList.size() != 0) {
                    queList.addAll(questionnaireInfoList);
                }
                refurbish();
            }

            @Override
            public Type getType() {
                return new TypeToken<ArrayList<QuestionnaireInfo>>() {
                }.getType();
            }
        });
    }

    @Override
    protected void initListener() {
        mRefreshLayout.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {//下拉刷新
            @Override
            public void onRefresh() {
                textView.setText("正在刷新");
                imageView.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                getData(1);
            }

            @Override
            public void onPullDistance(int distance) {
            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "松开刷新" : "下拉刷新");
                imageView.setVisibility(View.VISIBLE);
                imageView.setRotation(enable ? 180 : 0);
            }
        });
        mRefreshLayout.setOnPushLoadMoreListener(new SuperSwipeRefreshLayout.OnPushLoadMoreListener() {//上拉加载
            @Override
            public void onLoadMore() {
                if (false) {
                    footerTextView.setText("正在加载...");
                    footerImageView.setVisibility(View.GONE);
                    footerProgressBar.setVisibility(View.VISIBLE);
                } else {
                    footerTextView.setText("没有更多数据");
                    footerImageView.setVisibility(View.GONE);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            footerImageView.setVisibility(View.VISIBLE);
                            mRefreshLayout.setLoadMore(false);
                            questionAdapter.notifyDataSetChanged();
                        }
                    }, 500);
                }
            }

            @Override
            public void onPushEnable(boolean enable) {
                footerTextView.setText(enable ? "松开加载" : "上拉加载");
                footerImageView.setVisibility(View.VISIBLE);
                footerImageView.setRotation(enable ? 0 : 180);
            }

            @Override
            public void onPushDistance(int distance) {
            }
        });
    }

    private View createHeaderView() {//设置头布局
        View headerView = LayoutInflater.from(mRefreshLayout.getContext()).inflate(R.layout.layout_head, null);
        progressBar = (ProgressBar) headerView.findViewById(R.id.pb_view);
        textView = (TextView) headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        imageView = (ImageView) headerView.findViewById(R.id.image_view);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(R.drawable.xlistview_arrow);
        progressBar.setVisibility(View.GONE);
        return headerView;
    }

    private View createFooterView() {//设置脚布局
        View footerView = LayoutInflater.from(mRefreshLayout.getContext()).inflate(R.layout.layout_footer, null);
        footerProgressBar = (ProgressBar) footerView.findViewById(R.id.footer_pb_view);
        footerImageView = (ImageView) footerView.findViewById(R.id.footer_image_view);
        footerTextView = (TextView) footerView.findViewById(R.id.footer_text_view);
        footerProgressBar.setVisibility(View.GONE);
        footerImageView.setVisibility(View.VISIBLE);
        footerImageView.setImageResource(R.drawable.xlistview_arrow);
        footerTextView.setText("上拉加载更多...");
        return footerView;
    }

    /**
     * 刷新
     */
    private void refurbish() {
        footerImageView.setVisibility(View.VISIBLE);
        footerProgressBar.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
        mRefreshLayout.setRefreshing(false);
        mRefreshLayout.setLoadMore(false);
        questionAdapter.notifyDataSetChanged();
        rlvQuestionnaireList.setVisibility(queList.size() == 0 ? View.GONE : View.VISIBLE);
        tvNotData.setVisibility(queList.size() == 0 ? View.VISIBLE : View.GONE);
    }

    /**
     * 跳转到问卷详情界面
     */
    private void toQuestionDetailActivity(int position) {
        Intent intent = new Intent(this, QuestionnaireDetailActivity.class);
        intent.putExtra("queId", queList.get(position).getId());
        startActivityForResult(intent, 1000);
    }

    private class QuestionAdapter extends RecyclerView.Adapter<QuestionHolder> {
        @Override
        public QuestionHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View customView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_questionnaire_list, parent, false);
            return new QuestionHolder(customView);
        }

        @Override
        public void onBindViewHolder(QuestionHolder holder, final int position) {
            QuestionnaireInfo info =  queList.get(position);
            if ("y".equals(info.getQuestionnaireUserInfo().getIsFinish())) {
                holder.imgQuestionnaireStatus.setImageResource(R.drawable.img_submit);
            } else {
                holder.imgQuestionnaireStatus.setImageResource(R.drawable.img_un_submit);
            }
            holder.tvQuestionnaireTitle.setText(info.getTitle());
            holder.tvQuestionnaireContent.setText(info.getIntroduction());
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {//点击事件
                    toQuestionDetailActivity(position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return queList.size();
        }
    }

    private static class QuestionHolder extends RecyclerView.ViewHolder {

        /**
         * 标题
         */
        private TextView tvQuestionnaireTitle;
        /**
         * 内容
         */
        private TextView tvQuestionnaireContent;
        /**
         * 状态
         */
        private ImageView imgQuestionnaireStatus;

        public QuestionHolder(View itemView) {
            super(itemView);
            imgQuestionnaireStatus = (ImageView) itemView.findViewById(R.id.img_questionnaire_status);
            tvQuestionnaireTitle = (TextView) itemView.findViewById(R.id.tv_questionnaire_title);
            tvQuestionnaireContent = (TextView) itemView.findViewById(R.id.tv_questionnaire_content);
        }
    }

    @Override
    protected  void onActivityResult(int requestCode, int resultCode, Intent data)  {
        super.onActivityResult(requestCode, resultCode,  data);
        if (requestCode == 1000) {
            getData(1);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NewActionHelp.cancel(this);
    }
}
